import React, { useEffect, useState, Fragment } from "react";
import {
  Button,
  Input,
  Select,
  Table,
  Divider,
  message,
  Popconfirm,
  Modal,
  Badge,
  Form,
  Row,
  Col,
  Alert,
  Upload
} from "antd";
import { connect } from "dva";
import preview from "../../../assets/preview.png";
import styles from "./TemplateManager.less";
import {
  getMessageTemplateList,
  deleteMessageTemplate,
  updateTemplateStatus
} from "../services/messageTemplateApi";
import api from "../../../services/publicApi";
import ToggleColumns from "../../../components/toggleColumns";
import useMultiPageRowSelection from "../../../hooks/useMultiPageRowSelection";
import { getCurrentTenant } from "../../../utils/utils";

function TemplateManager(props) {
  const { history, form, userData } = props;
  const { getFieldDecorator, getFieldsValue, validateFields } = form;
  const [listData, setListData] = useState([]); // 表格数据
  // const [deptList, setDeptList] = useState([]); // 归属部门列表数据
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [loading, setloading] = useState(false);
  // 导入文件状态
  const [fileUploading, setFileUploading] = useState(false);
  // const [searchTime, setSearchTime] = useState([]); // 创建时间范围筛选条件
  // const [templateName, setTemplateName] = useState(""); // 模板名称筛选条件
  // const [ascOrDesc, setAscOrDesc] = useState("DESC"); // 升序/降序
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewContent, setPreviewContent] = useState("");
  const [showColumns, setShowColumns] = useState([]);
  const [columnCfg, setcolumnCfg] = useState({});
  // const [type, setType] = useState(1);
  const [
    selectedRowKeys,
    onSelectChange,
    resetRowSelection
  ] = useMultiPageRowSelection(listData, "templateId");

  // const previewContentList = previewContent.split("\n");
  let previewContentTitle;
  // if (type === 1) {
  //   previewContentTitle = previewContentList.shift();
  // }
  // 获取列表数据
  const getMessageTemplateListData = () => {
    setloading(true);
    const params = {
      pageNum,
      pageSize,
      ...getFieldsValue()
    };
    getMessageTemplateList(params).then(res => {
      if (res.success) {
        setListData(res.datas);
        setTotal(res.totalCount);
      } else {
        message.error(res.errMsg);
      }
      setloading(false);
    });
  };
  useEffect(() => {
    getMessageTemplateListData();
  }, [
    // templateName,
    // searchTime,
    pageNum,
    pageSize
  ]);

  const handleCommit = record => {
    const params = {
      // ...record,
      templateId: record.templateId,
      isEnabled: record.isEnabled === "Y" ? "N" : "Y"
    };
    const msg = record.isEnabled === "Y" ? "停用成功" : "启用成功";
    updateTemplateStatus(params).then(res => {
      if (res.success) {
        message.success(msg);
        getMessageTemplateListData();
      } else {
        message.error(res.errMsg);
      }
    });
    return true;
  };
  const handleDelete = templateId => {
    deleteMessageTemplate({ templateId, isDeleted: "Y" }).then(res => {
      if (res.success) {
        message.success("删除成功");
        getMessageTemplateListData();
      } else {
        message.error(res.errMsg);
      }
    });
  };
  const handlePreview = record => {
    setPreviewContent(record.templateContent);
    setPreviewVisible(true);
    // setType(record.type);
  };

  const handlePageChange = page => {
    setPageNum(page);
  };
  const handlePageSizeChange = (_, size) => {
    setPageSize(size);
    setPageNum(1);
  };

  const handleSubmit = () => {
    // getMessageTemplateListData();
    validateFields(err => {
      if (!err) {
        resetRowSelection();
        getMessageTemplateListData();
      }
    });
  };

  const onReset = () => {
    form.resetFields();
    resetRowSelection();
    getMessageTemplateListData();
  };

  const originColumns = [
    {
      title: "序号",
      dataIndex: "id",
      width: 50,
      render: (a, b, c) => <span>{pageSize * (pageNum - 1) + c + 1}</span>
    },
    {
      title: "租户编码",
      ellipsis: true,
      width: 100,
      dataIndex: "tenantCode"
    },
    {
      title: "租户名称",
      ellipsis: true,
      width: 100,
      dataIndex: "tenantName"
    },
    {
      title: "消息模版编码",
      ellipsis: true,
      dataIndex: "templateCode"
    },
    {
      title: "消息模版名称",
      ellipsis: true,
      dataIndex: "templateName"
    },
    {
      title: "消息模版标题",
      ellipsis: true,
      dataIndex: "templateTitle"
    },
    {
      title: "来源",
      ellipsis: true,
      dataIndex: "creator",
      render: text => <span>{text || "--"}创建</span>
    },
    {
      title: "状态",
      width: 80,
      dataIndex: "isEnabled",
      render: text => {
        let res;
        switch (text) {
          case "Y":
            res = <Badge status="success" text="启用" />;
            break;
          case "N":
            res = <Badge status="default" text="停用" />;
            break;
          default:
            res = "";
        }
        return res;
      }
    },
    {
      title: "备注",
      ellipsis: true,
      dataIndex: "description"
    },
    {
      title: "预览模板",
      dataIndex: "preview",
      // fixed: "right",
      render: (text, record) => (
        <a onClick={() => handlePreview(record)}>预览</a>
      )
    },
    {
      title: "操作",
      dataIndex: "handle",
      width: 160,
      fixed: "right",
      render: (text, record) => {
        const isDisable = record.isEnabled === "Y";
        const offLineTitle =
          record.isEnabled === "Y" ? "确定停用模板吗" : "确定启用模板吗";
        return (
          <div>
            <a
              disabled={isDisable}
              onClick={() =>
                history.push(
                  `/messageCenter/templateManager/add?templateId=${record.templateId}`
                )
              }
            >
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定删除这一模板吗"
              onConfirm={() => handleDelete(record.templateId)}
            >
              <a disabled={isDisable}>删除</a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              title={offLineTitle}
              onConfirm={() => handleCommit(record)}
            >
              {record.isEnabled === "Y" ? (
                <a>停用</a>
              ) : (
                <a disabled={isDisable}>启用</a>
              )}
            </Popconfirm>
          </div>
        );
      }
    }
  ];

  useEffect(() => {
    const { userInfo = {} } = userData;
    // 获取隐藏表格配置
    api
      .getColumnsByTable({ user: userInfo.userId, tag: "template" })
      .then(res => {
        if (res.success) {
          setcolumnCfg(res.datas[0] || {});
          if (res.datas.length === 0 || res.datas[0].config === "") {
            setShowColumns(originColumns);
          } else {
            const hiddenArr = res.datas[0].config.split(",");
            setShowColumns(
              originColumns.filter(
                c => !hiddenArr.find(hc => hc === c.dataIndex)
              )
            );
          }
        } else {
          message.error(res.errMsg);
        }
      });
  }, []);

  const onSetColumns = (shows, hiddens) => {
    const { userInfo = {} } = userData;
    setShowColumns(shows);
    // 同步动态表格隐藏列信息
    api
      .updateColumnsByTable({
        config: hiddens.map(h => h.dataIndex).join(","),
        user: userInfo.userId,
        tag: columnCfg.tag || "template",
        id: columnCfg.id
      })
      .then(res => {
        if (!res.success) {
          message.warning("动态表格同步失败");
        }
      });
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 }
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 }
    }
  };

  return (
    <div className={styles.root}>
      <div className={styles.titleBox}>模板列表</div>
      <div className={styles.topSearch}>
        <div className={styles.rightSearch}>
          <Form {...formItemLayout} onSubmit={handleSubmit}>
            <Row>
              <Col span={6}>
                <Form.Item
                  label="消息模版编码"
                  labelCol={{ span: 10 }}
                  wrapperCol={{ span: 14 }}
                >
                  {getFieldDecorator("templateCode")(
                    <Input placeholder="请输入" />
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  label="消息模版名称"
                  labelCol={{ span: 10 }}
                  wrapperCol={{ span: 14 }}
                >
                  {getFieldDecorator("templateName")(
                    <Input placeholder="请输入" />
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="创建人">
                  {getFieldDecorator("creator")(<Input placeholder="请输入" />)}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="状态">
                  {getFieldDecorator("isEnabled")(
                    <Select placeholder="请选择" allowClear>
                      <Select.Option value="Y">启用</Select.Option>
                      <Select.Option value="N">停用</Select.Option>
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={18}></Col>
              <Col span={6} style={{ textAlign: "right" }}>
                <Button style={{ marginRight: "10px" }} onClick={onReset}>
                  重置
                </Button>
                <Button type="primary" onClick={handleSubmit}>
                  搜索
                </Button>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className={styles.tableBox}>
        <div className={styles.tableTopBox}>
          <div>
            <Upload
              showUploadList={false}
              name="excel"
              action="/mgt/excel/importMessageTemplateExcel"
              data={{ tenantCode: getCurrentTenant().tenantCode[0] }}
              onChange={e => {
                const { status, response } = e.file;
                if (status === "uploading") {
                  setFileUploading(true);
                } else if (status === "done") {
                  // 如果上传返回有错误，则提示错误信息，重置 loading 状态
                  if (response && response.errCode === 1) {
                    message.error(response.errMsg);
                  } else {
                    message.success("导入成功");
                    // 重新加载列表，重置搜索表单
                    onReset();
                  }
                  setFileUploading(false);
                }
              }}
            >
              <Button
                disabled={getCurrentTenant().id === "100000"}
                type="primary"
                loading={fileUploading}
              >
                导入
              </Button>
            </Upload>
            <Button
              type="dashed"
              style={{ marginLeft: 10 }}
              onClick={() => {
                window.console.log(window.routerBase);
                window.open(
                  `${
                    window.location.href.indexOf("mgt-web") !== -1
                      ? "/mgt-web/"
                      : "/"
                  }message.xlsx`,
                  "_blank"
                );
              }}
            >
              导入模版下载
            </Button>
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={() => {
                window.open(
                  `/mgt/excel/outputMessageTemplateExcel?param=${selectedRowKeys.join(
                    ","
                  )}`,
                  "_blank"
                );
              }}
              disabled={selectedRowKeys.length === 0}
            >
              批量导出
            </Button>
            {selectedRowKeys.length !== 0 && (
              <Fragment>
                <Alert
                  style={{
                    display: "inline-block",
                    padding: "5px 8px",
                    marginLeft: 10
                  }}
                  message={`已选中 ${selectedRowKeys.length} 条记录`}
                  type="info"
                />
              </Fragment>
            )}
          </div>
          <div>
            <ToggleColumns
              originColumns={originColumns}
              showColumns={showColumns}
              onSetColumns={onSetColumns}
            />
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={() => history.push("/messageCenter/templateManager/add")}
              disabled={getCurrentTenant().id === "100000"}
            >
              新建模板
            </Button>
          </div>
        </div>
        <Table
          dataSource={listData}
          columns={showColumns}
          rowKey="templateId"
          scroll={{ x: 1300 }}
          loading={loading}
          rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
          // onChange={handleFilter}
          pagination={{
            current: pageNum,
            pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            total,
            onChange: handlePageChange,
            onShowSizeChange: handlePageSizeChange,
            showTotal: () => `共有${total}条`
          }}
        />
      </div>
      <Modal
        className={styles.modal}
        visible={previewVisible}
        title={false}
        footer={false}
        bodyStyle={{
          background: `url(${preview}) no-repeat`,
          backgroundSize: "241px 490px",
          backgroundPosition: "center center",
          padding: 0,
          display: "flex",
          justifyContent: "center"
        }}
        onCancel={() => setPreviewVisible(false)}
        closable={false}
      >
        <div className={styles.preview}>
          <div className={styles.previewContent}>
            {previewContentTitle && (
              <div style={{ fontWeight: "bold" }}>{previewContentTitle}</div>
            )}
            {previewContent}
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default connect(stores => ({
  userData: stores.user
}))(Form.create()(TemplateManager));
